package com.zzyl.intercept;

import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtConfigProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtConfigProperties jwtConfigProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果不是映射到方法就放行, 比如跨域验证请求, 静态资源等不需要身份校验的请求
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //获取header中的token
        String token = request.getHeader(Constants.USER_TOKEN);
        log.info("customerUserToken:===================={}", token);
        //判断token是否为空 为空抛异常
        if (StringUtils.isEmpty(token)) {
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        //解析token
        Claims claims = JwtUtil.parseJWT(jwtConfigProperties.getBase64encodedsecretkey(), token);
        //判断解析是否成功
        if (claims == null) {
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        //获取数据 用户id
        Object userIdObj = claims.get(Constants.JWT_USERID);
        Long userId = Long.valueOf(userIdObj.toString());
        //判断数据是否为空
        if (userId == null) {
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        //将用户id存到ThreadLocal中
        UserThreadLocal.set(userId);
        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理ThreadLocal中的数据, 防止内存泄漏, 内存泄漏可能会导致内存溢出
        UserThreadLocal.remove();
    }
}
